package com.define.ssh.action.account;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.DeptAccount;
import com.define.ssh.model.Func;
import com.define.ssh.model.Role;
import com.define.ssh.model.UserFunc;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.service.DeptAccountService;
import com.define.ssh.service.FuncService;
import com.define.ssh.service.RoleService;
import com.define.ssh.service.UserFuncService;
import com.define.ssh.service.UserInfoService;
import com.define.ssh.util.InterfaceIpData;

/**
 * 账号管理
 * 
 */
@ParentPackage("admin")
public class AccountAction extends BaseAdminAction {

	/** 页面传递参数过来 */
	protected int pageSize;
	protected int pageNum;

	@Resource(name = "userInfoServiceImpl")
	private UserInfoService userInfoService;

	@Resource(name = "roleServiceImpl")
	private RoleService roleService;

	@Resource(name = "funcServiceImpl")
	private FuncService funcService;

	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;

	@Resource(name = "userFuncServiceImpl")
	private UserFuncService userFuncService;

	@Resource(name = "deptAccountServiceImpl")
	private DeptAccountService deptAccountService;

	private UserInfo userInfo;

	private List<Role> roleList;// 所有角色

	private String userCode;
	private String deptIds;
	private String funcIds;
	private String remark;
	private long roleid;
	private String pwd;

	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		pager.setSearchMap(searchMap);
		pager = this.userInfoService.findPagerByAccount(pager);
		roleList = roleService.getAllList();
		this.saveLog("账号管理", "查看列表：" + pager.getPageNumber());
		return "list";
	}

	/**
	 * 检测用户输入的用户是否通过
	 * 
	 * @return
	 */
	public String checkUser() {
		if (userCode.equals("")) {
			return ajax(Status.error, "请输入用户");
		}
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("userCode", userCode);
		final List<UserInfo> list = userInfoService
				.getAllListByParameter(searchMap);
		if (list.size() == 0) {
			return ajax(Status.error, "用户不存在");
		}
		if (list.size() == 1) {
			final UserInfo user = list.get(0);
			
			if (user.getRole()==null||user.getRole().getId()==0) {
				return ajax(Status.success, "成功");
			} else {
				return ajax(Status.error, "账号用户已存在");
			}
		}
		return ajax(Status.error, "用户输入错误，请重新输入");
	}

	/**
	 * 取功能菜单树数据
	 * 
	 * @return
	 */
	public String getFuncTree() {
		final List<Func> list = this.funcService.getAllList();
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final Func func = list.get(i);
			sb.append("{");
			sb.append("id:" + func.getId());
			sb.append(",pId:" + func.getParentId());
			sb.append(",name:\"" + func.getName() + "\"");
			if (func.getParentId().equals("0")) {
				sb.append(",open:true");
			}
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getDeptTree() {
		//final List<Compdept> list = this.compdeptService.getAllList();
		final DetachedCriteria dt = DetachedCriteria
				.forClass(Compdept.class);
		dt.add(Restrictions.eq("company.id",InterfaceIpData.compid));
		final List<Compdept> list = this.compdeptService.findByCriteria(dt);
		
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final Compdept dept = list.get(i);
			sb.append("{");
			sb.append("id:" + dept.getId());
			sb.append(",pId:" + dept.getPid());
			sb.append(",name:\"" + dept.getDeptname() + "\"");
			if (dept.getPid().equals("0")) {
				sb.append(",open:true");
			}
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	/**
	 * 取关联的部门数据
	 * 
	 * @return
	 */
	public String getDeptTreeIds() {
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("userid", Integer.parseInt(userInfo.getId() + ""));
		final List<DeptAccount> list = this.deptAccountService
				.getAllListByParameter(searchMap);
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final DeptAccount du = list.get(i);
			sb.append("{");
			sb.append("id:" + du.getDeptid());
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	/**
	 * 取关联的菜单数据
	 * 
	 * @return
	 */
	public String getFuncTreeIds() {
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("user.id", userInfo.getId());
		final List<UserFunc> list = this.userFuncService
				.getAllListByParameter(searchMap);
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final UserFunc uf = list.get(i);
			sb.append("{");
			sb.append("id:" + uf.getFunc().getId());
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	// 删除
	public String delete() {
		final UserInfo ui = this.userInfoService.get(userInfo.getId());
		ui.setRole(null);
		ui.setRemark("");
		saveLog("账号管理", "删除账号：" + ui.getUserCode());
		this.deptAccountService.delDeptAccountByUserId(ui.getId());// 删除关联部门
		this.userFuncService.delUserFuncByUserId(ui.getId());// 删除关联功能
		this.userInfoService.update(ui);
		return ajax(Status.success, "删除成功!");
	}

	// 编辑
	public String edit() {
		final UserInfo ui = this.userInfoService.get(userInfo.getId());
		return ajax(ui);
	}

	// 保存
	public String save() {
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("userCode", userCode);
		final List<UserInfo> list = userInfoService
				.getAllListByParameter(searchMap);
		if (list.size() == 1) {
			final UserInfo user = list.get(0);
			// 查询角色
			user.setRole(roleService.get(roleid));
			user.setRemark(remark);
			user.setPassword(pwd);
			//
			// 保存用户对应的菜单记录
			this.userFuncService.delUserFuncByUserId(user.getId());
			for (final String funcid : funcIds.split(",")) {
				if (!funcid.equals("")) {
					final UserFunc uf = new UserFunc();
					uf.setFunc(this.funcService.get(Long.parseLong(funcid)));
					uf.setUser(user);
					this.userFuncService.save(uf);
				}
			}
			// 保存用户对应的部门记录
			
			this.deptAccountService.delDeptAccountByUserId(user.getId());
			
			List<Object[]> daList=new ArrayList<Object[]>();
			for (final String deptid : deptIds.split(",")) {
				if (!deptid.equals("")) {
					Object[] da=new Object[]{Integer.parseInt(deptid),Integer.parseInt(user.getId() + "")};
					daList.add(da);
				}
			}

			String deptname = ""; 
			DetachedCriteria dc=DetachedCriteria.forClass(Compdept.class);
			dc.add(Restrictions.sqlRestriction(" id in (select deptid from deptuser where userid="+user.getId()+")"));
			List<Compdept> deptlist=this.compdeptService.findByCriteria(dc);
			for(Compdept dept:deptlist){
				if(deptname.equals("")){
					deptname += dept.getDeptname();
				}else{
					deptname +=","+ dept.getDeptname();
				}
				
			}
				
			 
			
			this.deptAccountService.save(daList);
			user.setDeptname(deptname);
			this.userInfoService.update(user);
		} else {

		}
		return ajax(Status.success, "添加成功");
	}

	// 更新
	public String update() {
		Long begin=new Date().getTime();
		final UserInfo user = this.userInfoService.get(userInfo.getId());
		// 查询角色
		//user.setRole(roleService.get(roleid));
		user.setRemark(remark);
		//
		// 保存用户对应的菜单记录
		this.userFuncService.delUserFuncByUserId(user.getId());
		for (final String funcid : funcIds.split(",")) {
			if (!funcid.equals("")) {
				final UserFunc uf = new UserFunc();
				uf.setFunc(this.funcService.get(Long.parseLong(funcid)));
				uf.setUser(user);
				this.userFuncService.save(uf);
			}
		}
		// 保存用户对应的部门记录
		 
		this.deptAccountService.delDeptAccountByUserId(user.getId());
		List<Object[]> daList=new ArrayList<Object[]>();
		for (final String deptid : deptIds.split(",")) {
			if (!deptid.equals("")) {
				Object[] da=new Object[]{Integer.parseInt(deptid),Integer.parseInt(user.getId() + "")};
				daList.add(da);
				 
			}
		}
		this.deptAccountService.save(daList);
		
		String deptname = ""; 
		DetachedCriteria dc=DetachedCriteria.forClass(Compdept.class);
		dc.add(Restrictions.sqlRestriction(" id in (select deptid from deptuser where userid="+user.getId()+")"));
		List<Compdept> deptlist=this.compdeptService.findByCriteria(dc);
		for(Compdept dept:deptlist){
			if(deptname.equals("")){
				deptname += dept.getDeptname();
			}else{
				deptname +=","+ dept.getDeptname();
			}
			
		}
		user.setDeptname(deptname);
		user.setPassword(pwd);
		this.userInfoService.update(user);
		long end=new Date().getTime();
		System.out.println(((end-begin)/1000));
		return ajax(Status.success, "修改成功");
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public String getUserCode() {
		return userCode;
	}

	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}

	public String getDeptIds() {
		return deptIds;
	}

	public void setDeptIds(String deptIds) {
		this.deptIds = deptIds;
	}

	public String getFuncIds() {
		return funcIds;
	}

	public void setFuncIds(String funcIds) {
		this.funcIds = funcIds;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public long getRoleid() {
		return roleid;
	}

	public void setRoleid(long roleid) {
		this.roleid = roleid;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

}